package com.kgc.web.filter; /**
 * <h3>项目名称:demo03050</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-08 13:04</p>
 **/

import javax.servlet.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/*通过注解方式配置过滤器*/
@WebFilter(filterName = "EncodingFilter",
        urlPatterns = {"/*"},initParams = {@WebInitParam(name = "encode",value = "UTF-8")})
public class EncodingFilter implements Filter {
    //声明成员变量，接收初始化参数
    private String encode;

    public void init(FilterConfig config) throws ServletException {
        //获取初始化配置里的参数
        encode=config.getInitParameter("encode");
        System.out.println("EncodingFilter对象实例化--初始化。。。");
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //过滤请求
        request.setCharacterEncoding(encode);
        System.out.println("过滤请求。。。");
        //请求放行
        chain.doFilter(request, response);
        System.out.println("过滤响应。。。");
        //过滤响应
        response.setContentType("text/html;charset="+encode);
    }
}
